﻿using System;
using System.ComponentModel;

namespace HeritageAcademy.Models.ViewModels
{
    /// <summary>
    /// Represents a value with a user-friendly name that can be selected by the user.
    /// </summary>
    public class AnswerViewModel : INotifyPropertyChanged, IComparable<AnswerViewModel>
    {
        #region Parameters

        const int UNSET_SORT_VALUE = Int32.MinValue;
        bool _isSelected;
        readonly int _sortValue;

        #endregion

        #region Ctor

        public AnswerViewModel() : this(UNSET_SORT_VALUE)
        {
        }

        public AnswerViewModel(int sortValue)
        {
            _sortValue = sortValue;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Returns the user-friendly name of this option.
        /// </summary>
        public string Tag { get; set; }

        /// <summary>
        /// Gets/sets whether this option is in the selected state.
        /// When this property is set to a new value, this object's
        /// PropertyChanged event is raised.
        /// </summary>
        public bool IsSelected
        {
            get { return _isSelected; }
            set
            {
                if (value == _isSelected)
                    return;

                _isSelected = value;
                OnPropertyChanged("IsSelected");
            }
        }

        /// <summary>
        /// Returns the value used to sort this option.
        /// The default sort value is Int32.MinValue.
        /// </summary>
        public int SortValue
        {
            get { return _sortValue; }
        }

        #endregion

        #region IComparable<AnswerViewModel> Members

        public int CompareTo(AnswerViewModel other)
        {
            if (other == null)
                return -1;

            if (SortValue == UNSET_SORT_VALUE && other.SortValue == UNSET_SORT_VALUE)
            {
                return Tag.CompareTo(other.Tag);
            }
            if (SortValue != UNSET_SORT_VALUE && other.SortValue != UNSET_SORT_VALUE)
            {
                return SortValue.CompareTo(other.SortValue);
            }
            if (SortValue != UNSET_SORT_VALUE && other.SortValue == UNSET_SORT_VALUE)
            {
                return -1;
            }
            return +1;
        }

        #endregion

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion
    }
}
